package neety.server;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.io.UnsupportedEncodingException;

/**
 * @Author: admin
 * @Description:
 * @Date: 2018/10/6 15:49
 */



public class ServerHandler extends ChannelInboundHandlerAdapter {

    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(ctx.channel().localAddress().toString()+"通道已激活.....");
    }

    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(ctx .channel().localAddress().toString()+"通道不活跃.....");
    }

    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf buf = (ByteBuf) msg;
        String rev = getMessage(buf);
        System.out.println("客户端收到服务器数据:" + rev);
        ctx.writeAndFlush(msg);
    }

    private String getMessage(ByteBuf buf) {
        byte[] con = new byte[buf.readableBytes()];
        buf.readBytes(con);
        try {
            return new String(con, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
    }

    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        System.out.println("接收数据完毕......");
        //ctx.writeAndFlush("hello neety");
        //ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
    }

    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
        System.out.println("NettyServer Handler Exception: " + cause.getMessage());
    }
}
